<template>
    <div class="portal-layout-preview">
        <a-float-button-group v-if="portalId" v-model:open="open" @click="myClick" trigger="click" type="primary" :style="{ right: '24px' }" @openChange="onOpenChange">
            <template #icon>
                <EditOutlined />
            </template>
            <a-float-button v-if="isDraggable" :tooltip="i18n('list.finishEdit','完成编辑')"  @click="finishEdit(layout)">
                <template #icon>
                    <CheckOutlined style="color:#389e0d"/>
                </template>
            </a-float-button>
            <a-float-button v-else :tooltip="i18n('list.editPage','编辑页面')"  @click="editPage()" >
                <template #icon>
                    <EditOutlined />
                </template>
            </a-float-button>
            <a-float-button :tooltip="i18n('list.addColumn','添加栏目')" @click="addColumn">
                <template #icon>
                    <PlusOutlined />
                </template>
            </a-float-button>
            <a-float-button :tooltip="i18n('list.directReturn','直接返回')" @click="notSaveAndReturn">
                <template #icon>
                    <RedoOutlined />
                </template>
            </a-float-button>

            <a-float-button :tooltip="i18n('list.restore','还原')" @click="restorePortal">
                <template #icon>
                    <HistoryOutlined />
                </template>
            </a-float-button>

        </a-float-button-group>
        <grid-layout
            :layout.sync="layout"
            :col-num="24"
            :row-height="2"
            :is-draggable="isDraggable"
            :is-resizable="isResizable"
            :is-mirrored="false"
            :vertical-compact="true"
            :autoSize="true"
            :margin="[10, 10]"
            :use-css-transforms="true"
        >
            <grid-item
                v-for="item in layout"
                :x="item.x"
                :y="item.y"
                :w="item.w"
                :h="item.h"
                :i="item.i"
                :key="item.i"
            >
                <div class="gridLayoutClass"
                     @click="editObj(item,false)">
                    <div class="headPClass" v-if="isDraggable">
                        <span class="btnSpan2" @click="removeObj(item.i)">
                                <DeleteOutlined :title="$ti18('rxList.delBtn','删除')" />
                        </span>
                    </div>
                    <!-- 控件内容-->
                    <div class="FormCustomControl">
                        <FormCustomControl :portalId="portalId" :item="item" :ref="item.id" :readonly="true"></FormCustomControl>
                    </div>
                </div>
            </grid-item>
        </grid-layout>
        <a-drawer
            placement="right"
            @close.stop="closeDrawer"
            width="400"
            :destroyOnClose="true"
            :visible="showDrawer"
            :z-index="9999"
            :closable="true"
            title="添加栏目"
        >
            <PortalLayoutPreviewAdd :portalId="portalId" @column="getColumn"></PortalLayoutPreviewAdd>
        </a-drawer>
    </div>
</template>

<script>
/**
 * 门户
 */
import FormCustomControl from "@/views/modules/form/FormCustomView/GridLayoutView/FormCustomControl.vue";
import {Util} from '@lowcode/jpaas-base-lib';
import { GridLayout, GridItem } from 'vue-grid-layout';
import InsPortalUserDefApi from "@/common/api/portal/insPortalUserDef.js";
import InsPortalDefApi from "@/common/api/portal/insPortalDef.js";
import useMain from "@/stores/useMain.js";
import { mapState } from 'pinia';
import PortalLayoutPreviewAdd from "./PortalLayoutPreviewAdd.vue"
import formCustomViewEvent from "@/views/modules/form/FormCustomView/js/formCustomViewEvent.js"

export default {
    name: "PortalLayoutPreview",
    components: {
        FormCustomControl,
        GridLayout,
        GridItem,
        PortalLayoutPreviewAdd
    },
    mixins:[formCustomViewEvent],
    computed: {
        ...mapState(useMain, ['curApp']),
    },
    props:{
        portId:{},
        //这个是从DialogView打开时需要用到的。
        menuParams:{},
        appId:{}
    },
    data() {
        return {
            open:false,
            layout:[],
            indexNum: 0,
            isOpenThis: false,//是否进入当前组件
            isDraggable: false,//是否可拖拽
            isResizable: false,//是否可编辑大小
            isEdit: 0,//门户是否允许编辑
            moduleId: '',
            portalId: "",//当前门户id
            showDrawer: false,//是否显示抽屉
        }
    },
    created(){
        this.isOpenThis = true;
        this.init();
        document.addEventListener('click',function onClick(){

        })
    },
    activated() {
        this.isOpenThis = true;
    },
    deactivated() {
        this.isOpenThis = false;
    },
    methods: {
        editPage(){
            this.isDraggable = open;
            this.isResizable = open;
        },
        onOpenChange(open){
            if(this.isResizable){
                open = true
            }
            this.open = open ;

        },
        i18n(name, text, key) {
            return this.$ti18(name, text, "PortalLayoutPreview", key);
        },
        init() {
            if (this.portId) {
                this.getLayoutListByPortalId();
            } else {
                let alias = this.getAlias();
                if (alias) {
                    this.getLayoutListByPortalKey(alias);
                } else {
                    this.getLayoutListByLoginUser();
                }
            }
        },
        getAlias() {
            let alias = "";
            if (this.$route.meta.params) {
                try {
                    let json = JSON.parse(this.$route.meta.params);
                    alias = json.alias;
                }catch (e){
                    let message = e;
                }

            } else if (this.$route.params) {
                alias = this.$route.params.alias;
            } else if (this.menuParams) {
                let params = JSON.parse(this.menuParams);
                alias = params.alias;
            }
            return alias;
        },
        //应用内获取首页门户
        getHomePage() {
            let self_=this;
            let appId = this.appId || this.curApp.appId
            if(!appId){
                return;
            }
            InsPortalDefApi.getCurUserPortalByAppId(appId).then(res=>{
                if(res.success && res.data && res.data.layoutJson){
                    self_.isEdit = res.data.isEdit;
                    self_.portalId = res.data.portId;
                    self_.layout = JSON.parse(res.data.layoutJson);
                    self_.$emit("setPortalId",self_.portalId);
                }
            });
        },
        getLayoutListByPortalKey(key) {
            return InsPortalDefApi.getLayoutListByPortalKey(key).then(res => {
                if (res && res.columns.length > 0) {
                    this.indexNum = res.columns.length;
                    this.layout = res.columns;
                }
            });
        },
        getLayoutListByPortalId() {
            return InsPortalDefApi.getLayoutListByPortalId(this.portId).then(res => {
                if (res && res.columns.length > 0) {
                    this.indexNum = res.columns.length;
                    this.layout = res.columns;
                }
            });
        },
        getLayoutListByLoginUser() {
            let appId = this.appId || this.curApp.appId
            if(appId){
                this.getHomePage();
                return;
            }
            let self_ = this;
            return InsPortalDefApi.getLayoutListByLoginUser().then(res => {
                if(res){
                    self_.isEdit = res.isEdit;
                    self_.portalId = res.portId;
                    if (res.columns.length > 0) {
                        self_.indexNum = res.columns.length;
                        self_.layout = res.columns;
                    }
                }
            });
        },
        //直接返回
        notSaveAndReturn() {
            this.isDraggable = false;
            this.isResizable = false;
            this.open = false;
            this.getLayoutListByLoginUser();
        },
        //添加栏目
        addColumn() {
            this.showDrawer = true;
        },
        closeDrawer() {
            this.isDraggable = true;
            this.isResizable = true;
            this.showDrawer = false;
            this.open = true;
        },
        //完成编辑
        finishEdit(values) {
            this.isDraggable = false;
            this.isResizable = false;
            let parameter = {
                portId: this.portalId,
                layoutList: this.layout,
            }
            return InsPortalUserDefApi.saveAll(parameter);
        },
        //获取添加的栏目
        getColumn(column) {
            this.layout.push(column);
        },
        editObj(item, showDrawer) {
            this.moduleid = item.id;
        },
        removeObj(key) {
            let layout = this.layout
            for (let i = 0; i < layout.length; i++) {
                if (key == layout[i].i) {
                    //判断是否是选择的
                    if (this.selectId == layout[i].id) {
                        this.selectId = "";
                        this.supportConf = "";
                        this.support = "";
                    }
                    layout.splice(i, 1);
                    break
                }
            }
        },
        getModuleFliter(item){
            let _obj = {
                column:this.i18n('colCompo','栏目组件'),
                list:this.i18n('listCompo','列表组件'),
                form:this.i18n('formCompo','表单组件'),
                tree:this.i18n('treeCompo','树形组件'),
                chart:this.i18n('chartCompo','图表组件'),
                tab:this.i18n('tabCompo','tab组件'),
                ureport:this.i18n('uReportCompo','ureport组件'),
            }
            if(item.config && item.config.name){
                return item.config.name ;
            }else {
                return _obj[item.defConf] ;
            }
        },
        restorePortal() {
            let self = this;
            this.$confirm({
                title: self.$ti18('rxMsa.actionTips', '操作提示'),
                content: self.i18n('msa.tips', '你确定要还原成原始布局吗？'),
                okText: self.$ti18('rxForm.ackBtn', '确认'),
                cancelText: self.$ti18('rxForm.cancelBtn', '取消'),
                keyboard: true,
                zIndex: 999999,
                onOk: function () {
                    InsPortalUserDefApi.deleteUserPortalByUserIdAndPortalId(self.portalId).then(res => {
                        self.getLayoutListByLoginUser();
                        self.isDraggable = false;
                        return res;
                    })
                },
                onCancel() {
                },

            })
        },
        /**
         * tab组件处理事件
         * @param tabLayout
         */
        handleTabLayout(tabLayout,conf){
            for (let i = 0; i < tabLayout.config.tabs.length; i++) {
                let layout=tabLayout.config.tabs[i];
                if(!layout.config){
                    return;
                }
                if(!this.$refs[layout.id]){
                    return;
                }
                if(layout.defConf == "tabContainer"){
                    this.handleTabLayout(layout.config,conf);
                }else {
                    let control=this.$refs[layout.id][0];
                    //触发组件中的公共事件
                    if(control && control.$refs[layout.config.alias] && control.$refs[layout.config.alias].handPublicReceive){
                        control.$refs[layout.config.alias].handPublicEvent(conf);
                    }
                }
            }
        }
    },
    watch: {
        '$route': {
            handler: function (val) {
                //防止 因为keep-alive的原因 路由改变 这个方法一直被调用；
                if (!this.isOpenThis) {
                    return;
                }
                let alias = this.getAlias();
                if (alias) {
                    this.getLayoutListByPortalKey(alias);
                } else {
                    this.getLayoutListByLoginUser();
                }
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.gridLayoutClass{
    border: none!important;
    border-radius: 10px!important;
    position: relative;
}
.gridLayoutClass ::v-deep(.ant-input-affix-wrapper:has(.ant-input-suffix)) + .x-f-tooltip-container{
    right: 30px;
}
.gridLayoutClass ::v-deep(.ant-input) + .ant-input-suffix{
    position: absolute;
    right: 10px;
    z-index: 9;
}
.gridLayoutClass ::v-deep(.ant-input){
    margin-left: -10px;
    transform: translateX(10px);
}
.portal-layout-button {
    display: flex;
    justify-content: flex-end;
}
.portal-layout-button:empty{
    margin-top: 0;
}
.portal-layout-button button {
    margin-right: 10px;
}

.indexHome {
    width: 100%;
    height: 100%;
    overflow: auto;
    box-sizing: border-box;
    background-color: #f0f2f5;
}

.btnSpan {
    border-radius: 10px;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 18px;
    background: #1890ff;
    display: inline-block;
    margin-left: 6px;
    cursor: pointer;
}

.btnSpan2 {
    border-radius: 15px;
    width: 30px;
    height: 30px;
    line-height: 30px;
    color: white;
    text-align: center;
    background: #ff585a;
    display: inline-block;
    margin-right: 0;
    cursor: pointer;
    z-index: 99;
}

.tips-tit{
    display: inline-block;
    height: 20px;
    line-height: 20px;
    font-size: 12px;
    position: absolute;
    background: #f5f7fa;
    color: #a8aeb5;
    padding: 0 6px;
    border-radius: 0 0 12px 0;
    border: 1px solid #dadde0;
    border-left: 0;
    border-top: 0;
    left: 1px;
    top: 1px;
}
.select-tit{
    position: absolute;
    left: 0;
    font-size: 12px;
    color: #fff;
    background: #1890ff;
    display: inline-block;
    border: 1px solid #1890ff;
    border-top: 0;
    border-left: 0;
    height: 20px;
    line-height: 20px;
    padding: 0 6px;
    border-radius: 0 0 12px 0;
}
.gridLayoutClass {
    background: #fff !important;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
}

.FormCustomControl {
    height: 100%;
    width: 100%;
    position: relative;
}

.FormCustomControl-prohibit {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 20px;
    bottom: 20px;
    z-index: 9;
}

.headPClass {
    margin: 0;
    z-index: 999;
    position: absolute;
    top: 5px;
    right: 10px;

}

.btnSpan i {
    color: #fff;
    font-size: 10px;
    margin-top: 3px;
}

.gridLayoutClass {
    background: #fff;
    border: 1px solid #ddd;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column
}
.bodyDivClass {
    flex: 1;
    padding: 20px;
}

.toolTabs {
    height: 100%;
}

ul, li {
    list-style: none;
}
</style>
